package DAO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import Negocio.Vehiculo;


public class HibernateVehiculoDAO {
	
	private static HibernateVehiculoDAO instancia = null;
	private static SessionFactory sf = null;
	
	public static HibernateVehiculoDAO getInstancia(){
		if(instancia == null){
			instancia = new HibernateVehiculoDAO();
			sf = HibernateUtil.getSessionFactory();
		}
		
		return instancia;
	}
	
	public void guardarVehiculo(Vehiculo vehiculo) {
		try{
			Session session = sf.openSession();
			session.beginTransaction();
			session.persist(vehiculo);
			session.flush();
			session.getTransaction().commit();
			session.close();
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error al guardar un Vehiculo");
		}
		
	}

	public Vehiculo getVehiculo(String patente) {
		try{
			Session session = sf.openSession();
			session.beginTransaction();
			Query q = session.createQuery("from Vehiculo v left join fetch v.tareasMantenimientoRealizadas where v.patente = ?").setString(0, patente);
			Vehiculo vehiculo = (Vehiculo) q.uniqueResult();
			session.flush();
			session.getTransaction().commit();
			session.close();
			return vehiculo;
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error a cargar un Vehiculo");
		}
		return null;
	}
	
	public void updateVehiculo(Vehiculo veh) {
		try{
			Session session = sf.openSession();
			session.beginTransaction();
			session.saveOrUpdate(veh);
			session.flush();
			session.getTransaction().commit();
			session.close();
			System.out.println("Vehiculo Actualizado");
		}catch (Exception e){
			System.out.println(e);
	        System.out.println("Error al actualizar Vehiculo");
		}
	}

}
